package config;

import com.interceptor.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@MapperScan(basePackages = {"com.mapper"},sqlSessionFactoryRef = "sqlSessionFactory")
public class MyBatisConfig {


    //2 这个bean返回了一个 会话工厂的产品就是会话(数据库连接)（食品工厂的产品就是产品），这连接需要通过数据源加工产生（DataSource）
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //扫描 数据库和java entity 对应的配置文件，所在包是哪里
        sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/com/mapper/*Mapper.xml"));       //mybatis的xml文件路径
        sessionFactoryBean.setTypeAliasesPackage("com.entiy");//生成的实体类映射在那个包
        PageInterceptor pageInterceptor = new PageInterceptor();
        sessionFactoryBean.setPlugins(new Interceptor[]{pageInterceptor});
        return  sessionFactoryBean;
    }


    //1
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();//mapper扫描配置类
        mapperScannerConfigurer.setBasePackage("com.mapper");//指定了扫描的包
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");//设定了sqlsessionFactory的名字
        return mapperScannerConfigurer;
    }
}
